---
import { OPEN_GRAPH, SITE, type Frontmatter } from "../config";
import { SITE_URL } from "../utils/siteUrl";

export interface Props {
  frontmatter?: Frontmatter;
  type?: string;
}

const { frontmatter, type } = Astro.props as Props;

const canonicalUrl = new URL(Astro.url.pathname, Astro.site);

const formattedContentTitle = frontmatter
  ? `${frontmatter.title} 🚀 ${SITE.title}`
  : SITE.title;

const ogTitle = frontmatter ? frontmatter.title : SITE.title;
const ogDescription = frontmatter ? frontmatter.description : SITE.description;

const ogImageData = {
  title: ogTitle,
  description: ogDescription,
  pagePath: Astro.url.pathname,
};

const imageSrc =
  frontmatter?.image?.src ??
  `${SITE_URL}/og?${Object.entries(ogImageData)
    .map(([key, value]) => `${key}=${value}`)
    .join("&")}`;

const imageUrl = new URL(imageSrc, Astro.url.origin);
const imageAlt = frontmatter?.image?.alt ?? OPEN_GRAPH.image.alt;

const ogType = type ?? "article";
---

<!-- Page Metadata -->
<link rel="canonical" href={canonicalUrl} />
<meta name="description" property="og:description" content={SITE.description} />

<!-- OpenGraph Tags -->
<meta property="og:title" content={formattedContentTitle} />
<meta property="og:type" content={ogType} />
<meta property="og:url" content={canonicalUrl} />
<meta property="og:locale" content={SITE.defaultLanguage} />
<meta property="og:image" content={imageUrl} />
<meta property="og:image:alt" content={imageAlt} />
<meta property="og:site_name" content={SITE.title} />

<!-- Twitter Tags -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content={OPEN_GRAPH.twitter} />
<meta name="twitter:title" content={formattedContentTitle} />
<meta name="twitter:description" content={SITE.description} />
<meta name="twitter:image" content={imageUrl} />
<meta name="twitter:image:alt" content={imageAlt} />

<!--
  TODO: Add json+ld data, maybe https://schema.org/APIReference makes sense?
  Docs: https://developers.google.com/search/docs/advanced/structured-data/intro-structured-data
  https://www.npmjs.com/package/schema-dts seems like a great resource for implementing this.
  Even better, there's a React component that integrates with `schema-dts`: https://github.com/google/react-schemaorg
-->
